package bma.common.langutil.ai.common;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import bma.common.langutil.ai.stack.AIStack;
import bma.common.langutil.ai.stack.AIStackSimple;

/**
 * 
 * @author guanzhong
 * @since 1.0 (imported from BMA.ESP Project)
 * 
 * @param <ITEM_TYPE>
 */
public class AIIteratorJava<ITEM_TYPE> implements AIIterator<ITEM_TYPE> {

	private Iterator<ITEM_TYPE> delegate;

	public AIIteratorJava(Iterator<ITEM_TYPE> iter) {
		super();
		this.delegate = iter;
	}

	public Iterator<ITEM_TYPE> getDelegate() {
		return delegate;
	}

	public void setDelegate(Iterator<ITEM_TYPE> delegate) {
		this.delegate = delegate;
	}

	@Override
	public boolean hasNext(AIStack<Boolean> stack) {
		return stack.success(delegate.hasNext());
	}

	@Override
	public boolean next(AIStack<ITEM_TYPE> stack) {
		stack.success(delegate.next());
		return true;
	}

	public static <TYPE> List<TYPE> toList(AIStack<?> parent,
			AIIterator<TYPE> it) throws Exception {
		final List<TYPE> r = new LinkedList<TYPE>();
		AIStackSimple<Boolean> stack = new AIStackSimple<Boolean>(parent);
		AIIteratorTraverser<TYPE, Boolean> t = new AIIteratorTraverser<TYPE, Boolean>(
				stack, it) {

			@Override
			protected Evaluation handle(TYPE item) {
				r.add(item);
				return Evaluation.CONTINUE;
			}

			@Override
			protected boolean end() {
				return stack.success(true);
			}
		};
		t.execute();
		stack.get();
		return r;
	}
}
